package com.freemalll.merchant.service.impl;

import cn.hutool.core.thread.ExecutorBuilder;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.freemalll.common.core.exception.BusinessException;
import com.freemalll.merchant.common.CommonEnum;
import com.freemalll.merchant.constant.ConfigConstant;
import com.freemalll.merchant.domain.dto.DTOInterfaceParams;
import com.freemalll.merchant.domain.dto.PuDaoDto;
import com.freemalll.merchant.domain.dto.RiskAuditMappingDto;
import com.freemalll.merchant.domain.dto.risk.RiskEgDto;
import com.freemalll.merchant.domain.dto.risk.config.RiskEgConfig;
import com.freemalll.merchant.domain.entity.*;
import com.freemalll.merchant.domain.entity.coopManagement.MerAssetManage;
import com.freemalll.merchant.domain.entity.coopManagement.MerAssetManageDetail;
import com.freemalll.merchant.mapper.common.CommonMapper;
import com.freemalll.merchant.service.*;
import com.freemalll.merchant.service.coopManagement.MerAssetManageDetailService;
import com.freemalll.merchant.service.coopManagement.MerAssetManageService;
import com.freemalll.merchant.utils.ConfigUtil;
import com.freemalll.merchant.utils.DataNoUtil;
import com.freemalll.merchant.utils.DateUtil;
import com.freemalll.merchant.utils.HttpClientUtil;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class RiskEgServiceImpl implements RiskEgService {

    @Resource
    private QxbService qxbService;
    @Resource
    private MerLicenseService merLicenseService;
    @Resource
    private MerMerchantFormerNameService merMerchantFormerNameService;
    @Resource
    private MerAttachService merAttachService;
    @Resource
    private PuDaoService puDaoService;
    @Resource
    private CommonMapper commonMapper;
    @Resource
    private MerLegalInfoService merLegalInfoService;
    @Resource
    private MerMerchantService merMerchantService;
    @Resource
    private MerVenueInfoService merVenueInfoService;
    @Resource
    private MerRunInfoService merRunInfoService;
    @Resource
    private MerMedicalEduLicenseService merMedicalEduLicenseService;
    @Resource
    private MerInstallmentInfoService merInstallmentInfoService;
    @Resource
    private MerInstallmentInfoCompetitiveService merInstallmentInfoCompetitiveService;
    @Resource
    private MerAccountLicenseService merAccountLicenseService;
    @Resource
    private MerMedicalLicenseService merMedicalLicenseService;
    @Resource
    private MerMedicalEduIcpLicenseService merMedicalEduIcpLicenseService;
    @Resource
    private MerAssetManageService merAssetManageService;
    @Resource
    private MerAssetManageDetailService merAssetManageDetailService;
    @Resource
    private MerMerchantCapitalOrderService merMerchantCapitalOrderService;
    @Resource
    private MerMerchantRiskCapitalOrderService merMerchantRiskCapitalOrderService;
    @Resource
    private DataNoUtil dataNoUtil;
    @Resource
    private DateUtil dateUtil;

    //需要调用启信宝的接口类型
    protected static final List<String> interfaceTypeList = Arrays.asList(
            DTOInterfaceParams.QX_businessFace,
            DTOInterfaceParams.QX_simplifiedCancellation,
            DTOInterfaceParams.QX_cancellation_record,
            DTOInterfaceParams.QX_illegal,
            DTOInterfaceParams.QX_dishonestExecutedEnterprise,
            DTOInterfaceParams.QX_restrictingHighConsumption,
            DTOInterfaceParams.QX_abnormalOperation,
            DTOInterfaceParams.QX_equityPledge,
            DTOInterfaceParams.QX_equityFreeze,
            DTOInterfaceParams.QX_administrativeSanction,
            DTOInterfaceParams.QX_executedEnterprise,
            DTOInterfaceParams.QX_filingInformation,
            DTOInterfaceParams.QX_announcementOfCourtSession,
            DTOInterfaceParams.QX_courtNotice,
            DTOInterfaceParams.QX_changeRecord
    );


    public void getQxbInfo(String merId, String licenseCode, RiskEgDto riskEgDto) {
        Map<String, JSONObject> result = new ConcurrentHashMap<>();
        int corePoolSize = Math.min(interfaceTypeList.size(), 20);
        ThreadPoolExecutor executor = ExecutorBuilder.create()
                .setCorePoolSize(corePoolSize)
                .setMaxPoolSize(corePoolSize)
                .setKeepAliveTime(60L, TimeUnit.SECONDS)
                .setWorkQueue(new LinkedBlockingQueue<>(20))
                .setHandler(new ThreadPoolExecutor.DiscardPolicy())
                .build();
        // 等待所有任务完成
        CompletableFuture.allOf(interfaceTypeList.stream()
                .map(type -> CompletableFuture.runAsync(() -> {
                    String response = qxbService.getQxbInfoByType(merId, licenseCode, type);
                    JSONObject json = JSON.parseObject(response);
                    if ("200".equals(json.getString("code")) && "200".equals(json.getJSONObject("data").getString("status"))) {
                        result.put(type, json.getJSONObject("data").getJSONObject("data"));
                    }
                }, executor)).toArray(CompletableFuture[]::new)).join();

        // 关闭线程池
        executor.shutdown();
        try {
            // 最大等待 30 秒，超时则强制关闭
            if (!executor.awaitTermination(30, TimeUnit.SECONDS)) {
                executor.shutdownNow();
            }
        } catch (InterruptedException e) {
            executor.shutdownNow();
            Thread.currentThread().interrupt(); // 重新设置中断标志
        }

        // 组装 DTO
        result.forEach((type, json) -> updateDtoByType(riskEgDto, json, type, merId));
    }


    private void updateDtoByType(RiskEgDto dto, JSONObject json, String type, String merId) {
        /**
         * {
         * 	"data": {},
         * 	"sign": "02447370aebe444fab6d2c5a8090cf06",
         * 	"message": "查询无结果",
         * 	"status": "201"
         * }
         */
        switch (type) {
            //工商信息
            case DTOInterfaceParams.QX_businessFace:
                dto.setRegStatus(json.getString("new_status"));
                dto.setQXB_creditCode(json.getString("creditNo"));
                dto.setQXB_biz_name(json.getString("name"));
                dto.setQXB_legalPersonName(json.getString("operName"));
                //更新一下工商状态
                merLicenseService.update(Wrappers.<MerLicense>lambdaUpdate()
                        .eq(MerLicense::getMerId, merId)
                        .set(MerLicense::getBusinessStatus, json.getString("new_status")));
                //存在则不新增
                List<MerAttach> changesInBusinessStatus = merAttachService.list(Wrappers.<MerAttach>lambdaQuery().eq(MerAttach::getMerId, merId).eq(MerAttach::getConfigCode, "changes_in_business_status"));
                if (!CollectionUtils.isEmpty(changesInBusinessStatus)) {
                    break;
                }
                MerAttach business = new MerAttach();
                business.setMerId(merId);//商户ID
                business.setConfigName("经营状态变动");//名称
                business.setConfigCode("changes_in_business_status");//名称编码
                // 获取当前日期
                LocalDate currentDate = LocalDate.now();
                // 定义格式：yyyy-MM-dd
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
                // 格式化成字符串
                String formattedDate = currentDate.format(formatter);
                business.setEventData(formattedDate); // 请求日期
                business.setRiskLevel("低风险");//风险等级
                business.setEventDetail("企业经营状态为：" + json.getString("status"));
                business.setOpinion("人工核实");//初审意见
                business.setAttachType(2);//征信类附件统一为2
                merAttachService.save(business);
                break;
            case DTOInterfaceParams.QX_changeRecord:
                //保存商户曾用名
                JSONArray changeRecordArray = json.getJSONArray("items");
                changeRecordArray.forEach(item -> {
                    JSONObject jsonObject = (JSONObject) item;
                    if ("企业名称变更".equals(jsonObject.getString("type"))) {
                        MerMerchantFormerName merMerchantFormerName = new MerMerchantFormerName();
                        merMerchantFormerName.setMerId(merId);
                        merMerchantFormerName.setFormerName(jsonObject.getString("afterContent"));
                        merMerchantFormerNameService.save(merMerchantFormerName);
                        //已经存在名称变更则不在保存
                        List<MerAttach> list = merAttachService.list(Wrappers.<MerAttach>lambdaQuery().eq(MerAttach::getMerId, merId).eq(MerAttach::getConfigCode, "merchant_name_change"));
                        if (CollectionUtils.isEmpty(list)) {
                            return;
                        }
                        //近一年内，最近一次变更 名称变更
                        String changeDate = jsonObject.getString("changeDate");
                        if (dateUtil.isWithinOneYear(changeDate, 12)) {
                            MerAttach attach = new MerAttach();
                            attach.setMerId(merId);//商户ID
                            attach.setConfigName("名称变更");//名称
                            attach.setConfigCode("merchant_name_change");//名称编码
                            attach.setEventData(jsonObject.getString("changeDate")); // 变更日期
                            attach.setRiskLevel("低风险");//风险等级
                            String eventDetail = " 由:" + jsonObject.getString("beforeContent") +
                                    " 变更为:" + jsonObject.getString("afterContent");
                            attach.setEventDetail(eventDetail);
                            attach.setOpinion("人工核实");//初审意见
                            attach.setAttachType(2);//征信类附件统一为2
                            merAttachService.save(attach);
                        }
                    }
                    if ("负责人变更".equals(jsonObject.getString("type"))) {
                        //已经存在名称变更则不在保存
                        List<MerAttach> list = merAttachService.list(Wrappers.<MerAttach>lambdaQuery().eq(MerAttach::getMerId, merId).eq(MerAttach::getConfigCode, "legal_change"));
                        if (CollectionUtils.isEmpty(list)) {
                            return;
                        }
                        //近一年内，最近一次变更
                        String changeDate = jsonObject.getString("changeDate");
                        if (dateUtil.isWithinOneYear(changeDate, 12)) {
                            MerAttach attach = new MerAttach();
                            attach.setMerId(merId);//商户ID
                            attach.setConfigName("法人变更");//名称
                            attach.setConfigCode("legal_change");//名称编码
                            attach.setEventData(jsonObject.getString("changeDate")); // 变更日期
                            attach.setRiskLevel("低风险");//风险等级
                            String eventDetail = " 法定代表人从:" + jsonObject.getString("beforeContent") +
                                    " 变更为:" + jsonObject.getString("afterContent");
                            attach.setEventDetail(eventDetail);
                            attach.setOpinion("人工核实");//初审意见
                            attach.setAttachType(2);//征信类附件统一为2
                            merAttachService.save(attach);
                        }
                    }
                    if ("注册资金变更".equals(jsonObject.getString("type"))) {
                        //已经存在名称变更则不在保存
                        List<MerAttach> list = merAttachService.list(Wrappers.<MerAttach>lambdaQuery().eq(MerAttach::getMerId, merId).eq(MerAttach::getConfigCode, "change_of_registered_capital"));
                        if (CollectionUtils.isEmpty(list)) {
                            return;
                        }
                        //近一年内，最近一次变更
                        String changeDate = jsonObject.getString("changeDate");
                        if (dateUtil.isWithinOneYear(changeDate, 12)) {
                            MerAttach attach = new MerAttach();
                            attach.setMerId(merId);//商户ID
                            attach.setConfigName("注册资本变更");//名称
                            attach.setConfigCode("change_of_registered_capital");//名称编码
                            attach.setEventData(jsonObject.getString("changeDate")); // 变更日期
                            attach.setRiskLevel("低风险");//风险等级
                            String eventDetail = " 注册资本由:" + jsonObject.getString("beforeContent") +
                                    " 变更为:" + jsonObject.getString("afterContent");
                            attach.setEventDetail(eventDetail);
                            attach.setOpinion("人工核实");//初审意见
                            attach.setAttachType(2);//征信类附件统一为2
                            merAttachService.save(attach);
                        }
                    }

                    if ("经营范围变更".equals(jsonObject.getString("type"))) {
                        //已经存在名称变更则不在保存
                        List<MerAttach> list = merAttachService.list(Wrappers.<MerAttach>lambdaQuery().eq(MerAttach::getMerId, merId).eq(MerAttach::getConfigCode, "change_in_business_scope"));
                        if (CollectionUtils.isEmpty(list)) {
                            return;
                        }
                        //近一年内，最近一次变更
                        String changeDate = jsonObject.getString("changeDate");
                        if (dateUtil.isWithinOneYear(changeDate, 12)) {
                            MerAttach attach = new MerAttach();
                            attach.setMerId(merId);//商户ID
                            attach.setConfigName("经营范围变更");//名称
                            attach.setConfigCode("change_in_business_scope");//名称编码
                            attach.setEventData(jsonObject.getString("changeDate")); // 变更日期
                            attach.setRiskLevel("低风险");//风险等级
                            String eventDetail = " 变更前:" + jsonObject.getString("beforeContent") +
                                    " 变更后:" + jsonObject.getString("afterContent");
                            attach.setEventDetail(eventDetail);
                            attach.setOpinion("人工核实");//初审意见
                            attach.setAttachType(2);//征信类附件统一为2
                            merAttachService.save(attach);
                        }
                    }
                });
                break;
            case DTOInterfaceParams.QX_announcementOfCourtSession:
                //开庭公告
                JSONArray announcementOfCourtSessionArray = json.getJSONArray("items");
                announcementOfCourtSessionArray.forEach(item -> {
                    JSONObject jsonObject = (JSONObject) item;
                    //已经存在则不在保存
                    List<MerAttach> list = merAttachService.list(Wrappers.<MerAttach>lambdaQuery().eq(MerAttach::getMerId, merId).eq(MerAttach::getConfigCode, "announcement_of_court"));
                    if (CollectionUtils.isEmpty(list)) {
                        return;
                    }
                    //近6个月内所有变更记录
                    String changeDate = jsonObject.getString("changeDate");
                    if (dateUtil.isWithinOneYear(changeDate, 6) && jsonObject.getString("disabled").equals("0")) {
                        MerAttach attach = new MerAttach();
                        attach.setMerId(merId);//商户ID
                        attach.setConfigName("开庭公告");//名称
                        attach.setConfigCode("announcement_of_court");//名称编码
                        attach.setEventData(jsonObject.getString("hearing_date")); // 开庭日期
                        attach.setRiskLevel("中风险");//风险等级
                        JSONArray relatedCompanies = jsonObject.getJSONArray("related_companies");
                        String companiesName = relatedCompanies.stream()
                                .map(obj -> ((JSONObject) obj).getString("name"))
                                .collect(Collectors.joining("、"));
                        String eventDetail = " 案号:" + jsonObject.getString("case_no") +
                                " 案由:" + jsonObject.getString("case_reason") +
                                " 身份：" + jsonObject.getString("pure_role") +
                                " 当事人：" + companiesName +
                                " 开庭日期：" + jsonObject.getString("hearing_date");
                        attach.setEventDetail(eventDetail);
                        attach.setOpinion("人工核实");//初审意见
                        attach.setAttachType(2);//征信类附件统一为2
                        merAttachService.save(attach);
                    }
                });

                break;
            case DTOInterfaceParams.QX_courtNotice:
                //法院公告
                JSONArray courtNoticeArray = json.getJSONArray("items");
                courtNoticeArray.forEach(item -> {
                    JSONObject jsonObject = (JSONObject) item;
                    //已经存在则不在保存
                    List<MerAttach> list = merAttachService.list(Wrappers.<MerAttach>lambdaQuery().eq(MerAttach::getMerId, merId).eq(MerAttach::getConfigCode, "announcement_of_court"));
                    if (CollectionUtils.isEmpty(list)) {
                        return;
                    }
                    //近6个月内所有变更记录
                    String changeDate = jsonObject.getString("changeDate");
                    if (dateUtil.isWithinOneYear(changeDate, 6) && jsonObject.getString("disabled").equals("0")) {
                        MerAttach attach = new MerAttach();
                        attach.setMerId(merId);//商户ID
                        attach.setConfigName("法院公告");//名称
                        attach.setConfigCode("court_announcement");//名称编码
                        attach.setEventData(jsonObject.getString("date")); // 发布日期
                        attach.setRiskLevel("中风险");//风险等级
                        String eventDetail = " 法院:" + jsonObject.getString("court") +
                                " 当事人：" + jsonObject.getString("person") +
                                " 内容：" + jsonObject.getString("content");
                        attach.setEventDetail(eventDetail);
                        attach.setOpinion("人工核实");//初审意见
                        attach.setAttachType(2);//征信类附件统一为2
                        merAttachService.save(attach);
                    }
                });
                break;
            case DTOInterfaceParams.QX_simplifiedCancellation:
                //简易注销
                JSONArray simplifiedCancellationArray = json.getJSONArray("items");
                simplifiedCancellationArray.forEach(item -> {
                    JSONObject jsonObject = (JSONObject) item;
                    if (jsonObject.getInteger("is_history") == 0) {
                        dto.setIs_cancellation(1);
                        List<MerAttach> list = merAttachService.list(Wrappers.<MerAttach>lambdaQuery().eq(MerAttach::getMerId, merId).eq(MerAttach::getConfigCode, "simplified_cancel"));
                        if (CollectionUtils.isEmpty(list)) {
                            return;
                        }
                        MerAttach attach = new MerAttach();
                        attach.setMerId(merId);//商户ID
                        attach.setConfigName("简易注销");//名称
                        attach.setConfigCode("simplified_cancel");//名称编码
                        String noticePeriod = jsonObject.getString("notice_period");
                        String firstDateStr = noticePeriod.substring(0, 11);
                        DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern("yyyy年MM月dd日");
                        DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
                        LocalDate date = LocalDate.parse(firstDateStr, inputFormatter);
                        String formatted = date.format(outputFormatter);
                        attach.setEventData(formatted); // 设置事件日期字段
                        attach.setRiskLevel("高风险");//风险等级
                        String eventDetail = " 公告期:" + jsonObject.getString("notice_period") +
                                " 简易注销结果:" + jsonObject.getString("gs_sca_result");
                        attach.setEventDetail(eventDetail);
                        attach.setOpinion("人工核实");//初审意见
                        attach.setAttachType(2);//征信类附件统一为2
                        merAttachService.save(attach);
                    }
                });
                break;
            case DTOInterfaceParams.QX_executedEnterprise:
                //被执行人
                JSONArray executedEnterpriseArray = json.getJSONArray("items");
                executedEnterpriseArray.forEach(item -> {
                    JSONObject jsonObject = (JSONObject) item;
                    if (jsonObject.getString("disabled").equals("0")) {
                        dto.setIs_executed(1);
                        List<MerAttach> list = merAttachService.list(Wrappers.<MerAttach>lambdaQuery().eq(MerAttach::getMerId, merId).eq(MerAttach::getConfigCode, "executed_enterprise"));
                        if (CollectionUtils.isEmpty(list)) {
                            return;
                        }
                        MerAttach attach = new MerAttach();
                        attach.setMerId(merId);//商户ID
                        attach.setConfigName("被执行人");//名称
                        attach.setConfigCode("executed_enterprise");//名称编码
                        attach.setEventData(jsonObject.getString("case_date")); //立案日期
                        attach.setRiskLevel("高风险");//风险等级
                        String eventDetail = " 案号:" + jsonObject.getString("case_number") +
                                " 执行法院:" + jsonObject.getString("court") +
                                " 执行金额:" + jsonObject.getString("amount") +
                                " 立案时间:" + jsonObject.getString("case_date");
                        attach.setEventDetail(eventDetail);
                        attach.setOpinion("人工核实");//初审意见
                        attach.setAttachType(2);//征信类附件统一为2
                        merAttachService.save(attach);
                    }
                });

                break;
            case DTOInterfaceParams.QX_filingInformation:
                //立案信息
                JSONArray filingInformationArray = json.getJSONArray("items");
                filingInformationArray.forEach(item -> {
                    JSONObject jsonObject = (JSONObject) item;
                    //已经存在则不在保存
                    List<MerAttach> list = merAttachService.list(Wrappers.<MerAttach>lambdaQuery().eq(MerAttach::getMerId, merId).eq(MerAttach::getConfigCode, "filing_info"));
                    if (CollectionUtils.isEmpty(list)) {
                        return;
                    }
                    //近6个月内所有变更记录
                    String changeDate = jsonObject.getString("changeDate");
                    if (dateUtil.isWithinOneYear(changeDate, 6)) {
                        MerAttach attach = new MerAttach();
                        attach.setMerId(merId);//商户ID
                        attach.setConfigName("立案信息");//名称
                        attach.setConfigCode("filing_info");//名称编码
                        attach.setEventData(jsonObject.getString("hearing_date")); // 开庭日期
                        attach.setRiskLevel("中风险");//风险等级
                        JSONArray relatedCompanies = jsonObject.getJSONArray("related_items");
                        String companiesName = relatedCompanies.stream()
                                .map(obj -> ((JSONObject) obj).getString("role"))
                                .collect(Collectors.joining("、"));
                        String eventDetail = " 案号:" + jsonObject.getString("case_no") +
                                " 案由:" + jsonObject.getString("case_cause") +
                                " 当事人：" + companiesName +
                                " 案件状态：" + jsonObject.getString("case_status") +
                                " 立案日期：" + jsonObject.getString("start_date");
                        attach.setEventDetail(eventDetail);
                        attach.setOpinion("人工核实");//初审意见
                        attach.setAttachType(2);//征信类附件统一为2
                        merAttachService.save(attach);
                    }
                });

                break;
            case DTOInterfaceParams.QX_cancellation_record:
                //注销备案
                JSONArray cancellationRecordArray = json.getJSONArray("items");
                cancellationRecordArray.forEach(item -> {
                    JSONObject jsonObject = (JSONObject) item;
                    if (!jsonObject.getString("status").equals("2")) {
                        dto.setIs_cancellation_record(1);
                        List<MerAttach> list = merAttachService.list(Wrappers.<MerAttach>lambdaQuery().eq(MerAttach::getMerId, merId).eq(MerAttach::getConfigCode, "cancel_filing"));
                        if (CollectionUtils.isEmpty(list)) {
                            return;
                        }
                        MerAttach attach = new MerAttach();
                        attach.setMerId(merId);//商户ID
                        attach.setConfigName("注销备案");//名称
                        attach.setConfigCode("cancel_filing");//名称编码
                        attach.setEventData(jsonObject.getString("audit_reg_date")); //清算组备案日期
                        attach.setRiskLevel("高风险");//风险等级
                        String eventDetail = " 清算组备案日期:" + jsonObject.getString("audit_reg_date") +
                                " 注销原因:" + jsonObject.getString("logout_reason") +
                                " 登记机关:" + jsonObject.getString("belong_org");
                        attach.setEventDetail(eventDetail);
                        attach.setOpinion("人工核实");//初审意见
                        attach.setAttachType(2);//征信类附件统一为2
                        merAttachService.save(attach);
                    }
                });
                break;

            case DTOInterfaceParams.QX_illegal:
                // 严重违法
                JSONArray illegalArray = json.getJSONArray("execution");
                illegalArray.forEach(item -> {
                    JSONObject jsonObject = (JSONObject) item;
                    if (jsonObject.getString("is_history").equals("0")) {
                        dto.setIs_illegal(1);
                        List<MerAttach> list = merAttachService.list(Wrappers.<MerAttach>lambdaQuery().eq(MerAttach::getMerId, merId).eq(MerAttach::getConfigCode, "serious_illegality"));
                        if (CollectionUtils.isEmpty(list)) {
                            return;
                        }
                        MerAttach attach = new MerAttach();
                        attach.setMerId(merId);//商户ID
                        attach.setConfigName("严重违法");//名称
                        attach.setConfigCode("serious_illegality");//名称编码
                        attach.setEventData(jsonObject.getString("in_date")); //限制令发布日期
                        attach.setRiskLevel("高风险");//风险等级
                        String eventDetail = " 列入时间:" + jsonObject.getString("in_date") +
                                " 列入严重违法失信企业名单（黑名单）原因:" + jsonObject.getString("in_reason");
                        attach.setEventDetail(eventDetail);
                        attach.setOpinion("人工核实");//初审意见
                        attach.setAttachType(2);//征信类附件统一为2
                        merAttachService.save(attach);
                    }
                });
                break;

            case DTOInterfaceParams.QX_dishonestExecutedEnterprise:
                //失信被执行企业
                JSONArray dishonestExecutedEnterpriseArray = json.getJSONArray("items");
                dishonestExecutedEnterpriseArray.forEach(item -> {
                    JSONObject jsonObject = (JSONObject) item;
                    if (jsonObject.getString("disabled").equals("0")) {
                        dto.setIs_dishonesty(1);
                        List<MerAttach> list = merAttachService.list(Wrappers.<MerAttach>lambdaQuery().eq(MerAttach::getMerId, merId).eq(MerAttach::getConfigCode, "dishonest_execution"));
                        if (CollectionUtils.isEmpty(list)) {
                            return;
                        }
                        MerAttach attach = new MerAttach();
                        attach.setMerId(merId);//商户ID
                        attach.setConfigName("失信被执行");//名称
                        attach.setConfigCode("dishonest_execution");//名称编码
                        attach.setEventData(jsonObject.getString("publish_date")); //发布日期
                        attach.setRiskLevel("高风险");//风险等级
                        String eventDetail = " 执行标的:" + jsonObject.getString("amount") +
                                " 发布日期:" + jsonObject.getString("publish_date") +
                                " 执行法院:" + jsonObject.getString("court") +
                                " 失信被执行人行为具体情形：" + jsonObject.getString("execution_desc");
                        attach.setEventDetail(eventDetail);
                        attach.setOpinion("人工核实");//初审意见
                        attach.setAttachType(2);//征信类附件统一为2
                        merAttachService.save(attach);
                    }
                });
                break;

            case DTOInterfaceParams.QX_restrictingHighConsumption:
                //限制高消费
                JSONArray restrictingHighConsumptionArray = json.getJSONArray("items");
                restrictingHighConsumptionArray.forEach(item -> {
                    JSONObject jsonObject = (JSONObject) item;
                    if (jsonObject.getString("tag").equals("0")) {
                        dto.setIs_height_limit(1);
                        List<MerAttach> list = merAttachService.list(Wrappers.<MerAttach>lambdaQuery().eq(MerAttach::getMerId, merId).eq(MerAttach::getConfigCode, "restricting_high_consumption"));
                        if (CollectionUtils.isEmpty(list)) {
                            return;
                        }
                        MerAttach attach = new MerAttach();
                        attach.setMerId(merId);//商户ID
                        attach.setConfigName("限制高消费");//名称
                        attach.setConfigCode("restricting_high_consumption");//名称编码
                        attach.setEventData(jsonObject.getString("releaseDate")); //限制令发布日期
                        attach.setRiskLevel("高风险");//风险等级
                        String eventDetail = " 案号:" + jsonObject.getString("caseNo") +
                                " 案由:" + jsonObject.getString("caseReason") +
                                " 限消目标:" + jsonObject.getString("name") +
                                " 限制令发布日期:" + jsonObject.getString("releaseDate") +
                                " 立案时间：" + jsonObject.getString("filingDate");
                        attach.setEventDetail(eventDetail);
                        attach.setOpinion("人工核实");//初审意见
                        attach.setAttachType(2);//征信类附件统一为2
                        merAttachService.save(attach);
                    }
                });
                break;

            case DTOInterfaceParams.QX_abnormalOperation:
                //经营异常
                JSONArray abnormalOperationArray = json.getJSONArray("items");
                abnormalOperationArray.forEach(item -> {
                    JSONObject jsonObject = (JSONObject) item;
                    if (jsonObject.getString("disabled").equals("0")) {
                        dto.setIs_business_abnormal(1);
                        List<MerAttach> list = merAttachService.list(Wrappers.<MerAttach>lambdaQuery().eq(MerAttach::getMerId, merId).eq(MerAttach::getConfigCode, "abnormal_operation"));
                        if (CollectionUtils.isEmpty(list)) {
                            return;
                        }
                        MerAttach attach = new MerAttach();
                        attach.setMerId(merId);//商户ID
                        attach.setConfigName("经营异常");//名称
                        attach.setConfigCode("abnormal_operation");//名称编码
                        attach.setEventData(jsonObject.getString("inDate")); //列入时间
                        attach.setRiskLevel("中风险");//风险等级
                        String eventDetail = " 列入日期:" + jsonObject.getString("inDate") +
                                " 列入原因:" + jsonObject.getString("inReason") +
                                " 做出决定机关（列入）:" + jsonObject.getString("department");
                        attach.setEventDetail(eventDetail);
                        attach.setOpinion("人工核实");//初审意见
                        attach.setAttachType(2);//征信类附件统一为2
                        merAttachService.save(attach);
                    }
                });
                break;
            //股权出质
            case DTOInterfaceParams.QX_equityPledge:
                JSONArray equityPledgeArray = json.getJSONArray("items");
                equityPledgeArray.forEach(item -> {
                    JSONObject jsonObject = (JSONObject) item;
                    if (jsonObject.getString("disabled").equals("0")) {
                        dto.setEquity_pledge(1);
                        List<MerAttach> list = merAttachService.list(Wrappers.<MerAttach>lambdaQuery().eq(MerAttach::getMerId, merId).eq(MerAttach::getConfigCode, "equity_pledge"));
                        if (CollectionUtils.isEmpty(list)) {
                            return;
                        }
                        MerAttach attach = new MerAttach();
                        attach.setMerId(merId);//商户ID
                        attach.setConfigName("股权出质");//名称
                        attach.setConfigCode("equity_pledge");//名称编码
                        attach.setEventData(jsonObject.getString("date"));//股权出质登记日期
                        attach.setRiskLevel("中风险");//风险等级
                        String eventDetail = " 当前质押状态:" + jsonObject.getString("status") +
                                " 质押时间:" + jsonObject.getString("date") +
                                " 出质人:" + jsonObject.getString("pledgor") +
                                " 出质金额:" + jsonObject.getString("pledgor_amount") +
                                " 质权人:" + jsonObject.getString("pawnee");
                        attach.setEventDetail(eventDetail);
                        attach.setOpinion("人工核实");//初审意见
                        attach.setAttachType(2);//征信类附件统一为2
                        merAttachService.save(attach);
                    }
                });

                break;

            case DTOInterfaceParams.QX_equityFreeze:
                //股权冻结
                JSONArray equityFreezeArray = json.getJSONArray("items");
                equityFreezeArray.forEach(item -> {
                    JSONObject jsonObject = (JSONObject) item;
                    if (jsonObject.getString("disabled").equals("0")) {
                        dto.setEquity_freeze(1);
                        List<MerAttach> list = merAttachService.list(Wrappers.<MerAttach>lambdaQuery().eq(MerAttach::getMerId, merId).eq(MerAttach::getConfigCode, "equity_freeze"));
                        if (CollectionUtils.isEmpty(list)) {
                            return;
                        }
                        MerAttach attach = new MerAttach();
                        attach.setMerId(merId);//商户ID
                        attach.setConfigName("股权冻结");//名称
                        attach.setConfigCode("equity_freeze");//名称编码
                        attach.setEventData(jsonObject.getString("public_date"));//公示日期
                        attach.setRiskLevel("高风险");//风险等级
                        String eventDetail = " 决定文书号：" + jsonObject.getString("number") +
                                " 处罚日期：" + jsonObject.getString("date") +
                                " 违法类型：" + jsonObject.getString("illegal_type") +
                                " 处罚内容：" + jsonObject.getString("content");
                        attach.setEventDetail(eventDetail);
                        attach.setOpinion("人工核实");//初审意见
                        attach.setAttachType(2);//征信类附件统一为2
                        merAttachService.save(attach);
                    }
                });


                break;

            case DTOInterfaceParams.QX_administrativeSanction:
                //行政处罚
                JSONArray administrativeSanctionArray = json.getJSONArray("items");
                administrativeSanctionArray.forEach(item -> {
                    JSONObject jsonObject = (JSONObject) item;
                    if (jsonObject.getString("disabled").equals("0")) {
                        dto.setIs_administrative_penalty(1);
                        List<MerAttach> list = merAttachService.list(Wrappers.<MerAttach>lambdaQuery().eq(MerAttach::getMerId, merId).eq(MerAttach::getConfigCode, "administrative_penalty"));
                        if (CollectionUtils.isEmpty(list)) {
                            return;
                        }
                        MerAttach attach = new MerAttach();
                        attach.setMerId(merId);//商户ID
                        attach.setConfigName("行政处罚");//名称
                        attach.setConfigCode("administrative_penalty");//名称编码
                        attach.setEventData(jsonObject.getString("public_date"));//公示日期
                        attach.setRiskLevel("中风险");//风险等级
                        String eventDetail = " 执行通知文书号：" + jsonObject.getString("number") +
                                " 股权数额：" + jsonObject.getString("amount") +
                                " 被执行人：" + jsonObject.getString("be_executed_person") +
                                " 状态：" + jsonObject.getString("status") +
                                " 执行法院：" + jsonObject.getString("executive_court") +
                                " 失效日期：" + jsonObject.getJSONObject("lose_efficacy").getString("date");
                        attach.setEventDetail(eventDetail);
                        attach.setOpinion("人工核实");//初审意见
                        attach.setAttachType(2);//征信类附件统一为2
                        merAttachService.save(attach);
                    }
                });
                break;

            default:
                break;
        }
    }


    public String callRiskEg(RiskEgDto riskEgDto) {
        try {
            //获取风控系统账户
            RiskEgConfig properties = getRiskEgConfig();
            String url = properties.getUrl();
            JSONObject header = new JSONObject();
            header.put("Authorization", properties.getAuthorization());
            Map<String, Object> paramMap = new HashMap<>();
            // 引擎组id
            paramMap.put("groupId", properties.getApplyEngineId());
            // 关联引擎任务记录编号
            paramMap.put("recordNo", dataNoUtil.generateSerialNo("risk"));
            // 引擎的入参
            paramMap.put("params", riskEgDto);
            return HttpClientUtil.doPostTwo(url,
                    header, JSON.toJSONString(paramMap),
                    "风控引擎决策系统-提交初审接口",
                    "mainTable", riskEgDto.getMerchant_id(), 3);
        } catch (Exception e) {
            log.error("调用引擎失败,商户id:{}", riskEgDto.getMerchant_id(), e);
        }
        return null;
    }

    @Override
    public JSONObject submitRiskEg(String merId, CommonEnum.riskControlEngineType riskControlEngineType) {
        //商户信息
        MerMerchant merchant = merMerchantService.getById(merId);
        //获取营业执照信息
        MerLicense merLicense = merLicenseService.getOne(Wrappers.<MerLicense>lambdaQuery().eq(MerLicense::getMerId, merchant.getMerId()).last(" limit 1"));
        //1、通用参数
        RiskEgDto riskEgDto = this.getGeneralParameters(riskControlEngineType, merchant, merLicense);
        //2、根据步骤设置引擎入参
        switch (riskControlEngineType) {
            //提交审核
            case SUBMIT_PRELIMINARY_REVIEW:
                this.setUpSubmissionForReviewAndParticipation(riskEgDto, merchant, merLicense);
                break;
            //获取支持资方
            case OBTAIN_FUNDING:
                this.setSupportingInvestorsToParticipate(riskEgDto, merchant, merLicense);
                break;
            //获取等级和额度
            case OBTAIN_MERCHANT_LEVEL:
                this.setMerchantLevelParticipation(riskEgDto, merchant);
                break;
            default:
                throw BusinessException.businessParamsNotExist("引擎请求类型错误");
        }
        //调用引擎
        String result = this.callRiskEg(riskEgDto);
        JSONObject jsonObject = JSON.parseObject(result);
        boolean success = jsonObject != null && StringUtils.hasText(jsonObject.getString("responseCode")) && jsonObject.getString("responseCode").equals("200") &&
                jsonObject.getJSONObject("body") != null &&
                jsonObject.getJSONObject("body").getJSONObject("outputVariable") != null &&
                jsonObject.getJSONObject("body").getJSONObject("outputVariable").getJSONObject("outputinformation") != null;
        if (!success) {
            throw BusinessException.businessParamsNotExist("决策引擎提交初审失败，请联系管理员");
        }
        JSONObject data = jsonObject.getJSONObject("body").getJSONObject("outputVariable").getJSONObject("outputinformation");
        JSONObject resMap = new JSONObject();
        switch (riskControlEngineType) {
            case SUBMIT_PRELIMINARY_REVIEW:
                //审核结论N	拒绝 A	通过 Q	取消 J	补件
                String auditResult = data.getString("first_call");//不会为空
                String reasonCode = data.getString("reason_code");//可能为空
                List<RiskAuditMappingDto> auditMappingList = null;
                if (StringUtils.hasText(reasonCode)) {
                    //去掉空格
                    reasonCode = reasonCode.replace(" ", "");
                    if (reasonCode.contains("[") || reasonCode.contains("]")) {
                        reasonCode = reasonCode.replace("[", "").replace("]", "");
                    }
                    List<String> reasonList = Arrays.asList(reasonCode.split(","));
                    if (!StringUtils.hasText(auditResult)) {
                        break;
                    }
                    List<RiskAuditMappingDto> riskAuditMapping = ConfigUtil.getList(ConfigConstant.RISK_AUDIT_MAPPING, RiskAuditMappingDto.class);
                    if (riskAuditMapping != null) {
                        auditMappingList = riskAuditMapping.stream()
                                .filter(item -> reasonList.contains(item.getReasonCode())
                                        && item.getConclusionCode().equals(auditResult))
                                .collect(Collectors.toList());
                    }
                }

                //通过
                if (auditResult.equals("A")) {
                    resMap.put("auditResult", CommonEnum.auditType.INITIAL_REVIEW_PASSED.name());
                }
                //补件
                if (auditResult.equals("J") && auditMappingList != null) {
                    for (RiskAuditMappingDto auditMapping : auditMappingList) {
                        //根据merId和配置编码查询附件
                        MerAttach attach = merAttachService.getOne(Wrappers.<MerAttach>lambdaQuery()
                                .eq(MerAttach::getMerId, merId)
                                .eq(MerAttach::getConfigCode, auditMapping.getConfigCode())
                                .orderByDesc(MerAttach::getAddTime)
                                .last(" limit 1 "));
                        if (attach != null) {
                            attach.setAttachResult(auditMapping.getReason());
                            merAttachService.updateById(attach);
                        }
                    }
                    resMap.put("auditResult", CommonEnum.auditType.INITIAL_REVIEW_PASSED.name());
                }
                //取消或拒绝
                if (auditResult.equals("N") || auditResult.equals("Q")) {
                    List<String> reasons = new ArrayList<>();
                    if (auditMappingList != null) {
                        for (RiskAuditMappingDto auditMapping : auditMappingList) {
                            reasons.add(auditMapping.getReason());
                        }
                    }
                    //取消或拒绝原因
                    resMap.put("reason", String.join(",", reasons));
                    //映射状态
                    if (auditResult.equals("N")) {
                        resMap.put("auditResult", CommonEnum.auditType.INITIAL_REVIEW_REFUSED.name());
                    }
                    if (auditResult.equals("Q")) {
                        resMap.put("auditResult", CommonEnum.auditType.INITIAL_REVIEW_RETURNED.name());
                    }
                }
                break;
            case OBTAIN_FUNDING:
                //支持资方 返回值格式例如 海尔消金,泸州银行,消费贷-XW
                String supportFundrasing = data.getString("support_fundrasing");
                if (!StringUtils.hasText(supportFundrasing)) {
                    break;
                }
                // 生成可修改的资方列表
                List<String> capitalList = new ArrayList<>(Arrays.asList(supportFundrasing.split(",")));

                // 检查是否需要过滤保理
                boolean needFilterBaoli = Optional.ofNullable(merchant.getApplyPolicy())
                        .map(policy -> Arrays.asList(policy.split(",")))
                        .orElse(Collections.emptyList())
                        .contains("ZC10");

                if (needFilterBaoli) {
                    capitalList.removeIf("保理"::equals);
                }
                int rank = 1;
                for (int i = 0; i < capitalList.size(); i++) {
                    MerAssetManage assetManage = merAssetManageService.getOne(Wrappers.<MerAssetManage>lambdaQuery()
                            .eq(MerAssetManage::getSourceName, capitalList.get(i))
                            .last(" limit 1 "));
                    if (Objects.isNull(assetManage)) {
                        continue;
                    }
                    String sceneParentCategory;
                    if (merchant.getSceneParentCategory().equals(CommonEnum.sceneCategory.DJK.name())) {
                        sceneParentCategory = CommonEnum.supportingScenariosType.GREAT_HEALTH.name();
                    } else {
                        sceneParentCategory = CommonEnum.supportingScenariosType.EDUCATION.name();
                    }
                    MerAssetManageDetail merAssetManageDetail = merAssetManageDetailService.getOne(Wrappers.<MerAssetManageDetail>lambdaQuery()
                            .eq(MerAssetManageDetail::getSourceId, assetManage.getSourceId())
                            .eq(MerAssetManageDetail::getSupportingScenarios, sceneParentCategory));
                    if (Objects.isNull(merAssetManageDetail)) {
                        log.info("未查询到该场景分类下的资方配置信息，商户{}合作申请时将不会推送该资方作为合作资方:{}", merId, assetManage.getSourceName());
                        continue;
                    }
                    if (merAssetManageDetail.getEnableFlag() == 0) {
                        log.info("资方未启用，商户{} 合作申请时将不会推送该资方作为合作资方:{}", merId, assetManage.getSourceName());
                        continue;
                    }
//                    //1、选择暂停或终止合作后，合作申请时将不会推送该资方作为合作资方
//                    String sceneParentCategory;
//                    if (merchant.getSceneParentCategory().equals(CommonEnum.sceneCategory.DJK.name())) {
//                        sceneParentCategory = CommonEnum.supportingScenariosType.GREAT_HEALTH.name();
//                    } else {
//                        sceneParentCategory = CommonEnum.supportingScenariosType.EDUCATION.name();
//                    }
//                    MerAssetManageDetail merAssetManageDetail = merAssetManageDetailService.getOne(Wrappers.<MerAssetManageDetail>lambdaQuery()
//                            .eq(MerAssetManageDetail::getSourceId, assetManage.getSourceId())
//                            .eq(MerAssetManageDetail::getSupportingScenarios, sceneParentCategory));
//                    if (Objects.isNull(merAssetManageDetail)) {
//                        log.info("未查询到该场景分类下的资方配置信息，商户{}合作申请时将不会推送该资方作为合作资方:{}", merId, assetManage.getSourceName());
//                        continue;
//                    }
//                    //判断资方是否暂停合作或终止合作
//                    if (merAssetManageDetail.getCooperationStatus().equals(CommonEnum.cooperationStatusType.SUSPEND_COOPERATION.name())
//                            || merAssetManageDetail.getCooperationStatus().equals(CommonEnum.cooperationStatusType.TERMINATION_COOPERATION.name())) {
//                        log.info("资方非正常合作，商户{}合作申请时将不会推送该资方作为合作资方:{}", merId, assetManage.getSourceName());
//                        continue;
//                    }
//                    //2、商户营业执照省如果不在资方配置的区域限制内，则不推送该资方作为合作资方 李茂说的要管
                    if (merAssetManageDetail.getMerchantApproval() == 1 && !merAssetManageDetail.getMerRegionalRestrictions().equals("无限制")
                            && !merAssetManageDetail.getMerRegionalRestrictions().contains(merLicense.getLicenseProvince())) {
                        log.info("商户{}合作申请时将不会推送该资方作为合作资方:{},因为区域不满足", merId, assetManage.getSourceName());
                        continue;
                    }
                    List<MerMerchantCapitalOrder> list = merMerchantCapitalOrderService.list(Wrappers.<MerMerchantCapitalOrder>lambdaQuery()
                            .eq(MerMerchantCapitalOrder::getMerId, merId)
                            .eq(MerMerchantCapitalOrder::getSourceId, assetManage.getSourceId()));
                    if (CollectionUtils.isEmpty(list)) {
                        MerMerchantCapitalOrder capitalOrder = new MerMerchantCapitalOrder();
                        capitalOrder.setSourceId(assetManage.getSourceId());
                        capitalOrder.setSourceName(assetManage.getSourceName());
                        capitalOrder.setMerId(merId);
                        capitalOrder.setRanking(rank);
                        merMerchantCapitalOrderService.save(capitalOrder);
                    }
                    List<MerMerchantRiskCapitalOrder> riskCapitalOrders = merMerchantRiskCapitalOrderService.list(Wrappers.<MerMerchantRiskCapitalOrder>lambdaQuery()
                            .eq(MerMerchantRiskCapitalOrder::getMerId, merId)
                            .eq(MerMerchantRiskCapitalOrder::getSourceId, assetManage.getSourceId()));
                    if (CollectionUtils.isEmpty(riskCapitalOrders)) {
                        MerMerchantRiskCapitalOrder riskCapitalOrder = new MerMerchantRiskCapitalOrder();
                        riskCapitalOrder.setMerId(merId);
                        riskCapitalOrder.setSourceId(assetManage.getSourceId());
                        riskCapitalOrder.setSourceName(assetManage.getSourceName());
                        merMerchantRiskCapitalOrderService.save(riskCapitalOrder);
                    }
                    rank++;
                }
                break;
            case OBTAIN_MERCHANT_LEVEL:
                //大健康等级和额度
                if (merchant.getSceneParentCategory().equals(CommonEnum.sceneCategory.DJK.name())) {
                    resMap.put("merchantLevel", data.getString("YM_bizLevel"));
                    resMap.put("merchantAmount", data.getInteger("YM_bizAmount"));
                }
                //教育等级和额度
                if (merchant.getSceneParentCategory().equals(CommonEnum.sceneCategory.JY.name())) {
                    resMap.put("merchantLevel", data.getString("JY_bizLevel"));
                    resMap.put("merchantAmount", data.getInteger("JY_bizAmount"));
                }
                break;
            default:
                break;
        }
        return resMap;
    }

    /**
     * 获取商户等级额度入参
     *
     * @param riskEgDto 引擎入参
     * @param merchant  商户
     */
    private void setMerchantLevelParticipation(RiskEgDto riskEgDto, MerMerchant merchant) {
        MerRunInfo merRunInfo = merRunInfoService.getOne(Wrappers.<MerRunInfo>lambdaQuery().eq(MerRunInfo::getMerId, merchant.getMerId()).last(" limit 1"));
        MerVenueInfo venueInfo = merVenueInfoService.getOne(Wrappers.<MerVenueInfo>lambdaQuery().eq(MerVenueInfo::getMerId, merchant.getMerId()).last(" limit 1"));
        //教师人数
        riskEgDto.setTeacher_num(merRunInfo.getMerTeacherNum());
        //是否有办学许可证 1 有 0 无
        MerMedicalEduLicense eduLicense = merMedicalEduLicenseService.getOne(Wrappers.<MerMedicalEduLicense>lambdaQuery().eq(MerMedicalEduLicense::getMerId, merchant.getMerId()).last(" limit 1"));
        if (eduLicense != null) {
            riskEgDto.setSchool_license(1);
        } else {
            riskEgDto.setSchool_license(0);
        }
        MerLicense merLicense = merLicenseService.getOne(Wrappers.<MerLicense>lambdaQuery().eq(MerLicense::getMerId, merchant.getMerId()).last(" limit 1"));
        //商户所在城市
        String cityName = commonMapper.selectValueByCode(merLicense.getLicenseCity());
        riskEgDto.setBiz_city_name(cityName);
        //租赁年限
        if (venueInfo.getRentalType() == null || venueInfo.getRentalType() == 2 || !StringUtils.hasText(venueInfo.getVenueDateEnd()) || venueInfo.getVenueDateEnd().equals("9999-12-31")) {
            riskEgDto.setReal_estate_type(99);
            riskEgDto.setLeasemonths(999);
        } else {
            int yearsBetween = dateUtil.calculateYearsBetween(venueInfo.getVenueDateStart(), venueInfo.getVenueDateEnd());
            riskEgDto.setReal_estate_type(yearsBetween);
            int monthsBetween = dateUtil.getMonthsBetween(venueInfo.getVenueDateStart(), venueInfo.getVenueDateEnd());
            riskEgDto.setLeasemonths(monthsBetween);
        }
        //员工数量
        riskEgDto.setEmployee_count(merRunInfo.getMerStaffNum());
        //连锁店数
        riskEgDto.setBiz_shop_count(merRunInfo.getStoreNumber());
        //月分期金额
        MerInstallmentInfo installmentInfo = merInstallmentInfoService.getOne(Wrappers.<MerInstallmentInfo>lambdaQuery().eq(MerInstallmentInfo::getMerId, merchant.getMerId()).last(" limit 1 "));
        if (installmentInfo != null) {
            riskEgDto.setBiz_month_amount(installmentInfo.getMonthInstallmentQuantity());
        }
        //经营场地类型
        if (venueInfo.getRentalType() != null && venueInfo.getRentalType() == 1) {
            riskEgDto.setSite_type("租赁");
        } else {
            riskEgDto.setSite_type("自有产权");
        }
        //教育二级场景分类
        if (merchant.getSceneParentCategory().equals(CommonEnum.sceneCategory.JY.name())) {
            String valueAfterPipe = extractFirstValueAfterPipe(merchant.getSceneCategory());
            riskEgDto.setScene_classification(valueAfterPipe);
        }
        //年营业额
        riskEgDto.setSales_volume(merRunInfo.getMerAnnualTurnover());
        MerInstallmentInfo merInstallmentInfo = merInstallmentInfoService.getOne(Wrappers.<MerInstallmentInfo>lambdaQuery().eq(MerInstallmentInfo::getMerId, merchant.getMerId()).last(" limit 1"));
        long count = merInstallmentInfoCompetitiveService.count(Wrappers.<MerInstallmentInfoCompetitive>lambdaQuery().eq(MerInstallmentInfoCompetitive::getInstallmentId, merInstallmentInfo.getInstallmentId()));
        //合作竞品数
        riskEgDto.setNum_cooperative(count);
        //品牌性
        CommonEnum.brandType brandTypeEnum = CommonEnum.brandType.getBrandTypeByCode(merchant.getBrandType());
        if (brandTypeEnum != null) {
            riskEgDto.setBrand(brandTypeEnum.getDescription());
        }
    }

    /**
     * @param riskEgDto 引擎入参
     * @param merchant  商户
     */
    private void setSupportingInvestorsToParticipate(RiskEgDto riskEgDto, MerMerchant merchant, MerLicense merLicense) {
        //是否存在对公账户  0：存在对公账户；1：不存在对公账户 判断开户信息是否为空
        MerAccountLicense accountLicense = merAccountLicenseService.getOne(Wrappers.<MerAccountLicense>lambdaQuery().eq(MerAccountLicense::getMerId, merchant.getMerId()).last(" limit 1 "));
        if (accountLicense != null) {
            riskEgDto.setIs_corporate_account_null(0);
        } else {
            riskEgDto.setIs_corporate_account_null(1);
        }
        //执业许可时长（月） 计算公式和不同场景分类取值
        if (merchant.getSceneParentCategory().equals(CommonEnum.sceneCategory.DJK.name())) {
            MerMedicalLicense merMedicalLicense = merMedicalLicenseService.getOne(Wrappers.<MerMedicalLicense>lambdaQuery().eq(MerMedicalLicense::getMerId, merchant.getMerId()).last(" limit 1 "));
            int monthsBetween = dateUtil.getMonthsBetween(merMedicalLicense.getMedlValidateStart());
            riskEgDto.setLicensemonth(monthsBetween);
        } else {
            //教育先取办学许可证，办学许可证取不到再取ICP许可证
            MerMedicalEduLicense eduLicense = merMedicalEduLicenseService.getOne(Wrappers.<MerMedicalEduLicense>lambdaQuery().eq(MerMedicalEduLicense::getMerId, merchant.getMerId()).last(" limit 1 "));
            if (eduLicense != null) {
                if (StringUtils.hasText(eduLicense.getValidateStart())) {
                    int monthsBetween = dateUtil.getMonthsBetween(eduLicense.getValidateStart());
                    riskEgDto.setLicensemonth(monthsBetween);
                } else {
                    riskEgDto.setLicensemonth(99);
                }
            } else {
                MerMedicalEduIcpLicense icpLicense = merMedicalEduIcpLicenseService.getOne(Wrappers.<MerMedicalEduIcpLicense>lambdaQuery().eq(MerMedicalEduIcpLicense::getMerId, merchant.getMerId()).last(" limit 1 "));
                if (icpLicense != null) {
                    if (StringUtils.hasText(icpLicense.getValidateStart())) {
                        int monthsBetween = dateUtil.getMonthsBetween(icpLicense.getValidateStart());
                        riskEgDto.setLicensemonth(monthsBetween);
                    } else {
                        riskEgDto.setLicensemonth(99);
                    }
                }
            }
        }
        //省份
        //注册地址和商户所在省 需要转码
        String province = commonMapper.selectValueByCode(merLicense.getLicenseProvince());
        riskEgDto.setBiz_province(province);
    }

    /**
     * 提交初审入参
     *
     * @param riskEgDto 引擎入参
     * @param merchant  商户id
     */
    private void setUpSubmissionForReviewAndParticipation(RiskEgDto riskEgDto, MerMerchant merchant, MerLicense merLicense) {
        //获取法人信息
        MerLegalInfo merLegalInfo = merLegalInfoService.getOne(Wrappers.<MerLegalInfo>lambdaQuery().eq(MerLegalInfo::getMerId, merchant.getMerId()).last(" limit 1"));
        //获取启信宝信息
        //this.getQxbInfo(merchant.getMerId(), merLicense.getLicenseCode(), riskEgDto);
        //todo 先写死存续 正常是在getQxbInfo方法中通过第三方接口获取
        merLicenseService.update(Wrappers.<MerLicense>lambdaUpdate()
                .eq(MerLicense::getMerId, merchant.getMerId())
                .set(MerLicense::getBusinessStatus, "存续"));
        riskEgDto.setRegStatus("存续");
        riskEgDto.setQXB_creditCode(merLicense.getLicenseCode());
        riskEgDto.setQXB_biz_name(merchant.getMerName());
        riskEgDto.setQXB_legalPersonName(merLegalInfo.getLegalMan());
        MerAttach attach = new MerAttach();
        attach.setMerId(merchant.getMerId());//商户ID
        attach.setConfigName("行政处罚");//名称
        attach.setConfigCode("administrative_penalty");//名称编码
        attach.setEventData(String.valueOf(LocalDate.now()));//公示日期
        attach.setRiskLevel("中风险");//风险等级
        String eventDetail = " 执行通知文书号：" + "121311" +
                " 股权数额：" + 500 +
                " 被执行人：" + "张三" +
                " 状态：" + "执行中" +
                " 执行法院：" + "测试数据" +
                " 失效日期：" + LocalDate.now();
        attach.setEventDetail(eventDetail);
        attach.setOpinion("人工核实");//初审意见
        attach.setAttachType(2);//征信类附件统一为2
        merAttachService.save(attach);
        MerAttach attach1 = new MerAttach();
        attach1.setMerId(merchant.getMerId());//商户ID
        attach1.setConfigName("法人变更");//名称
        attach1.setConfigCode("legal_change");//名称编码
        attach1.setEventData(String.valueOf(LocalDate.now())); // 变更日期
        attach1.setRiskLevel("低风险");//风险等级
        String eventDetail1 = " 法定代表人从:" + "张三" +
                " 变更为:" + "李四";
        attach1.setEventDetail(eventDetail1);
        attach1.setOpinion("人工核实");//初审意见
        attach1.setAttachType(2);//征信类附件统一为2
        merAttachService.save(attach1);
        //经营范围
        riskEgDto.setBusinessScope(merLicense.getLicenseRunRange());
        //成立时间
        riskEgDto.setEstiblishDate(merLicense.getLicenseRegisterDate());
        //如果申请类型为主体变更 则需要将关联商户的成立时长传递给引擎
        if (merchant.getApplyType().equals(CommonEnum.applyType.SUBJECT_CHANGE.name())) {
            MerLicense history = merLicenseService.getOne(Wrappers.<MerLicense>lambdaQuery().eq(MerLicense::getMerId, merchant.getRelatedMerId()).last(" limit 1"));
            if (history != null) {
                int establishmentDuration = dateUtil.getMonthsBetween(history.getLicenseRegisterDate());
                riskEgDto.setEstiblishmonth_of_associated(establishmentDuration);
            }
        }
        //申请类型
        CommonEnum.applyType applyTypeByCode = CommonEnum.applyType.getApplyTypeByCode(merchant.getApplyType());
        if (applyTypeByCode != null) {
            riskEgDto.setApplication_type(applyTypeByCode.getDescription());
        }
        //法人姓名
        riskEgDto.setLegalPersonName(merLegalInfo.getLegalMan());
        //法人身份证有效期剩余天数
        int idCardValidDays = dateUtil.getValidDays(merLegalInfo.getLegalValidateEnd());
        riskEgDto.setLegalPersonIdcardValidDays(idCardValidDays);
        //法人身份证
        riskEgDto.setLegalPersonidcard(merLegalInfo.getLegalManIdCard());
        //注册地址和商户所在省 需要转码
        String province = commonMapper.selectValueByCode(merLicense.getLicenseProvince());
        riskEgDto.setBiz_province(province);
        String city = commonMapper.selectValueByCode(merLicense.getLicenseCity());
        String country = commonMapper.selectValueByCode(merLicense.getLicenseCountry());
        //注册地址
        riskEgDto.setRegLocation(province + city + country + merLicense.getLicenseAddress());
        //法人年龄 当前日期减去出身年月
        int age = dateUtil.calculateAge(merLegalInfo.getBirthday());
        riskEgDto.setLegalPersonAge(age);
        //调用朴道获取报告
        this.getTdInfo(riskEgDto, merLegalInfo);
        //统一社会编码
        riskEgDto.setCreditCode(merLicense.getLicenseCode());
        //特批订单 如果特殊申请不是无则设置1 否则 0
        if (merchant.getSpecialApply().equals("无")) {
            riskEgDto.setSpecial_approval(0);
        } else {
            riskEgDto.setSpecial_approval(1);
        }
        //注册资金
        riskEgDto.setBiz_reg_capital(merLicense.getLicenseCapital().toBigInteger().intValue());
        //商户名称
        riskEgDto.setBiz_name(merchant.getMerName());
        //营业执照有效期剩余天数  有限期止减去档期日期
        int licenseValidDays = dateUtil.getValidDays(merLicense.getLicenseValidateEnd());
        riskEgDto.setLicenseValidDays(licenseValidDays);
    }

    private RiskEgDto getGeneralParameters(CommonEnum.riskControlEngineType riskControlEngineType, MerMerchant merchant, MerLicense merLicense) {
        RiskEgDto riskEgDto = new RiskEgDto();
        switch (riskControlEngineType) {
            case SUBMIT_PRELIMINARY_REVIEW:
                riskEgDto.setCall_type(1);
                break;
            case OBTAIN_FUNDING:
                riskEgDto.setCall_type(2);
                break;
            case OBTAIN_MERCHANT_LEVEL:
                riskEgDto.setCall_type(3);
                break;
        }
        if (merchant.getSceneParentCategory().equals(CommonEnum.sceneCategory.DJK.name())) {
            riskEgDto.setBiz_type("1");
            riskEgDto.setScene_type(merchant.getSceneCategory());
        } else {
            riskEgDto.setBiz_type("2");
        }
        riskEgDto.setMerchant_id(merchant.getMerId());
        //成立时长
        int establishmentDuration = dateUtil.getMonthsBetween(merLicense.getLicenseRegisterDate());
        riskEgDto.setEstiblishmonth(establishmentDuration);
        //经营面积
        MerVenueInfo venueInfo = merVenueInfoService.getOne(Wrappers.<MerVenueInfo>lambdaQuery().eq(MerVenueInfo::getMerId, merchant.getMerId()).last("limit 1"));
        riskEgDto.setBiz_floor_area(venueInfo.getVenueArea());
        return riskEgDto;
    }

    /**
     * 同盾解析
     *
     * @param riskEgDto
     * @param corporateInfoDto
     */
    private void getTdInfo(RiskEgDto riskEgDto, MerLegalInfo corporateInfoDto) {
        if (riskEgDto == null || corporateInfoDto == null) {
            throw BusinessException.businessValidateError("参数不能为空");
        }
        if (!StringUtils.hasText(corporateInfoDto.getLegalManIdCard()) ||
                !StringUtils.hasText(corporateInfoDto.getLegalManPhone()) ||
                !StringUtils.hasText(corporateInfoDto.getLegalMan())) {
            throw BusinessException.businessValidateError("法人信息不完整");
        }
        //解析朴道报告 todo 先不调用征信查询
        //PuDaoDto puDaoDto = puDaoService.parsingData(corporateInfoDto);
        PuDaoDto puDaoDto = new PuDaoDto();
        if (puDaoDto == null) {
            return;
        }
        puDaoDto.setFinalScore(80);
        puDaoDto.setFinalDecision("通过");
        //填充数据
        riskEgDto.setLegalPerson_applyOneWeekNum(puDaoDto.getApplyOneWeekNum());
        riskEgDto.setLegalPerson_applyOneMonthNum(puDaoDto.getApplyOneMonthNum());
        riskEgDto.setLegalPerson_applyThreeMonthNum(puDaoDto.getApplyThreeMonthNum());
        riskEgDto.setLegalPerson_applySixMonthNum(puDaoDto.getApplySixMonthNum());
        riskEgDto.setLegalPerson_applyOneYearNum(puDaoDto.getApplyOneYearNum());
        riskEgDto.setLegalPerson_applyEighteenMonthNum(puDaoDto.getApplyEighteenMonthNum());
        riskEgDto.setLegalPerson_applyTwoYearNum(puDaoDto.getApplyTwoYearNum());
        riskEgDto.setLegalPerson_applySixtyMonthNum(puDaoDto.getApplySixtyMonthNum());
        riskEgDto.setLegalPerson_final_score(puDaoDto.getFinalScore());
        riskEgDto.setLegalPerson_final_decision(puDaoDto.getFinalDecision());

    }


    /**
     * 从形如 "JY03|JY032,JY03|JY033" 的字符串中提取第一个 | 后的值
     *
     * @param input 输入字符串
     * @return 提取到的值，如 "JY032"
     */
    public String extractFirstValueAfterPipe(String input) {
        if (input == null || input.isEmpty()) {
            return "";
        }

        // 第一步：按逗号分割，取第一个部分
        String[] parts = input.split(",");
        if (parts.length == 0) {
            return "";
        }
        String firstPart = parts[0];

        // 第二步：按竖线分割，取第二个部分
        String[] subParts = firstPart.split("\\|");
        if (subParts.length < 2) {
            return "";
        }

        return subParts[1];
    }


    private RiskEgConfig getRiskEgConfig() {
        String riskEngineApiExecuteImmediately = ConfigUtil.getCoValue(ConfigConstant.RISK_ENGINE_API_EXECUTE_IMMEDIATELY);
        if (!StringUtils.hasText(riskEngineApiExecuteImmediately)) {
            throw BusinessException.businessValidateError("未配置启信宝请求参数");
        }
        return JSON.parseObject(riskEngineApiExecuteImmediately, RiskEgConfig.class);
    }
}
